package com.sunyard.client2.conf;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import com.sunyard.client2.util.PropertiesUtil;
import com.sunyard.client2.util.StringUtil;

public class ConfUtil {
	
	public static final String confFile = "conf.properties";

	static Properties p;

	public static String getString(String key, String defaultValue) {
		if (p == null) {
			try {
				p = PropertiesUtil.loadConfigR(confFile);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return defaultValue;
			} catch (IOException e) {
				e.printStackTrace();
				return defaultValue;
			}
		}
		String v = p.getProperty(key);
		if (StringUtil.isNull(v)) {
			return defaultValue;
		} else {
			return v;
		}
	}
	
	public static boolean getBoolean(String key,boolean defaultValue){
		String v = getString(key, "");
		if(StringUtil.isNull(v)){
			return defaultValue;
		}
	    boolean r = Boolean.parseBoolean(v);
	    return r;
	}

	public static int getInt(String key, int defaultValue) {
		if (p == null) {
			try {
				p = PropertiesUtil.loadConfigR(confFile);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return defaultValue;
			} catch (IOException e) {
				e.printStackTrace();
				return defaultValue;
			}
		}
		String v = p.getProperty(key);
		if (StringUtil.isNull(v)) {
			return defaultValue;
		} else {
			return Integer.parseInt(v);
		}
	}

	public static float getFloat(String key, float defaultValue) {
		if (p == null) {
			try {
				p = PropertiesUtil.loadConfigR(confFile);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return defaultValue;
			} catch (IOException e) {
				e.printStackTrace();
				return defaultValue;
			}
		}
		String v = p.getProperty(key);
		if (StringUtil.isNull(v)) {
			return defaultValue;
		} else {
			return Float.parseFloat(v);
		}
	}

	public static void reload() {
		if (p != null) {
			p.clear();
			p = null;
		}
		getProperties();
	}

	public static Properties getProperties() {
		if (p == null) {
			try {
				p = PropertiesUtil.loadConfigR(confFile);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
				return null;
			}
		}
		return p;
	}

	public static void main(String[] args) {
		System.out.println(ConfUtil.getString("ip", "default"));
	}

}
